<template>
	<view class="content">
		<view class="contBox">
			<view class="top">
			</view> 
			<view class="center" v-if="loading">
				<view class="contdiv">
					定位中...
				</view>
			</view>
			<view class="center" v-else-if="!shopInfo">
				<view class="contdiv">
					定位失败
				</view>
				<view class="contTip">
					<u-icon name="map" color="#7C8288" size="16" style="margin-right: 10rpx;"></u-icon>
					{{locationError || '定位失败，请检查位置权限'}}
				</view>
			</view>
			<view class="center" v-else>
				<view 
					class="contdiv" 
					:style="{background: shopInfo ? (isRegistered ? 'linear-gradient(28deg, #00bd84,#00ce8f)' : 'linear-gradient(28deg, #ff6b6b,#ff8e8e)') : 'linear-gradient(28deg, #ff6b6b,#ff8e8e)'}" 
					@click="toPunchCard"
					:class="{disabled: !shopInfo}"
				>
					<view class="contText">
						{{buttonText}}
					</view>
					<view class="contTime">
						{{currentTime}}
					</view>
				</view>
				<view class="contTip" :class="shopInfo ? (isRegistered ? 'contTipS' : 'contTipE') : 'contTipE'">
					<u-icon 
						:name="shopInfo ? 'checkmark-circle-fill' : 'close-circle-fill'" 
						:color="shopInfo ? (isRegistered ? '#00b42a' : '#FF3939') : '#FF3939'" 
						size="16" 
						style="margin-right: 10rpx;"
					></u-icon>
					{{`您已进入"${shopInfo.name || '未知店铺'}"附近，可打卡`}}
				</view>
				<view class="contJl" @click="toUrl('/pages/index/checkInStatistics')">
					打卡统计
				</view>
			</view>
			<view class="bottom">
				<view class="bottomLi">
					已备案门店：<text style="color: #00b42a;">绿色</text>
				</view>
				<view class="bottomLi">
					未备案门店：<text style="color: #FF3939;">红色</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted, onUnmounted, computed } from 'vue';
	import { GETNearestShop } from '@/api/interface.js';
	import { onShow } from '@dcloudio/uni-app';
	
	const loading = ref(true);
	const shopInfo = ref(null);
	const locationError = ref('');
	const currentTime = ref('');
	let timer = null;
	
	// 按钮文案（仅依赖后端返回的 shopInfo.clockInAfterWork）
	const buttonText = computed(() => {
		if (!shopInfo.value) return '';
		return shopInfo.value.clockInAfterWork ? '离店打卡' : '进店打卡';
	});
	
	// 更新当前时间
	const updateTime = () => {
		const now = new Date();
		const hours = String(now.getHours()).padStart(2, '0');
		const minutes = String(now.getMinutes()).padStart(2, '0');
		const seconds = String(now.getSeconds()).padStart(2, '0');
		currentTime.value = `${hours}:${minutes}:${seconds}`;
	};
	
	// 获取高精度定位
	const getLocation = () => {
		loading.value = true;
		locationError.value = '';
		
		uni.getLocation({
			type: 'gcj02', // 坐标系类型
			altitude: true, // 高精度定位
			highAccuracyExpireTime: 3000, // 高精度定位超时时间
			success: (res) => {
				const { longitude, latitude } = res;
				// console.log('定位成功', longitude, latitude);
				// console.log('定位成功', 118.788536, 32.039994);
				getNearestShop(longitude, latitude);
				// getNearestShop(118.788536, 32.039994);
			},
			fail: (err) => {
				console.error('定位失败', err);
				loading.value = false;
				locationError.value = '定位失败，请检查位置权限是否开启';
				
				// 根据错误码显示具体错误信息
				switch(err.errCode) {
					case 1:
						locationError.value = '位置权限未授权，请在设置中开启权限';
						break;
					case 2:
						locationError.value = '位置不可用，请检查设备定位服务';
						break;
					case 3:
						locationError.value = '定位超时，请重试';
						break;
				}
			}
		});
	};
	
	// 获取最近的店铺
	const getNearestShop = async (longitude, latitude) => {
		try {
			const res = await GETNearestShop({
				longitude,
				latitude
			});
			
			console.log('获取店铺信息', res);
			if (res && res.code === 0 && res.data) {
				shopInfo.value = res.data;
			} else {
				locationError.value = res?.message || '未找到附近的店铺';
			}
		} catch (error) {
			console.error('获取店铺信息失败', error);
			locationError.value = '获取店铺信息失败，请重试';
		} finally {
			loading.value = false;
		}
	};
	
	// 跳转到打卡页面
	const toPunchCard = () => {
		if (shopInfo.value && isRegistered.value) {
			uni.setStorageSync('currentShop', shopInfo.value);
			uni.navigateTo({ url: '/pages/index/punchCard' });
		} else if (!shopInfo.value) {
			uni.showToast({ title: '该门店不可打卡', icon: 'none' });
		} else {
			uni.showToast({ title: '该门店未备案，不可打卡', icon: 'none' });
		}
	};
	
	const toUrl = (data) =>{
		uni.navigateTo({
			url:data
		});
	};
	
	onMounted(() => {
		// 初始化时间
		updateTime();
		// 设置定时器更新时间
		timer = setInterval(updateTime, 1000);
		// 获取定位
		getLocation();
	});
	
	// 页面显示时也刷新一次定位与店铺信息，确保按钮文案同步最新状态
	onShow(() => {
		getLocation();
	});
	
	onUnmounted(() => {
		// 清除定时器
		if (timer) {
			clearInterval(timer);
		}
	});
	// 新增：是否已备案计算属性（兼容 中文“是/否”）
	const isRegistered = computed(() => {
		const v = shopInfo.value?.isRegister;
		return String(v).trim() === '是';
	});
</script>

<style lang="scss" scoped>
	.content{
		width: 100%;
		height: 100vh;
		background: #F2F3F5;
		padding: 30rpx;
		box-sizing: border-box;
	}
	.contBox{
		width: 100%;
		height: 100%;
		border-radius: 19.23rpx 19.23rpx 19.23rpx 19.23rpx;
		background: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-around;
		flex-direction: column;
	}
	.top{
		width: 100%;
		height: 0rpx;
	}
	.center,
	.bottom{
		width: 100%;
	}
	.contdiv{
		width: 274.36rpx;
		height: 274.36rpx;
		border-radius: 50%;
		margin: 0 auto;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		background: linear-gradient(28deg, #00bd84,#00ce8f);
		box-shadow: 0 7.05rpx 15.38rpx 0 #00000026;
	}
	.contdiv.disabled{
		background: linear-gradient(28deg, #dcdddf,#e3e4e6) !important;
	}
	.contText{
		font-size: 38.46rpx;
		font-weight: 600;
	}
	.contTime{
		font-size: 28.21rpx;
		font-weight: 400;
		margin-left: 0;
		margin-top: 20rpx;
	}
	.contTip{
		width: 100%;
		font-size: 25.64rpx;
		font-weight: 400;
		color: #7C8288;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 48rpx;
	}
	.contTipS{
		color: #00b42a;
	}
	.contTipE{
		color: #FF3939;
	}
	.contJl{
		font-size: 25rpx;
		font-weight: 600;
		color: #1677FF;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 46.15rpx;
	}
	.bottom{
		margin-top: 115.38rpx;
		padding-bottom: 115.38rpx;
	}
	.bottomLi{
		width: 100%;
		text-align: center;
		font-size: 24.36rpx;
		font-weight: 400;
		color: #acb1b5;
		margin-top: 27rpx;
	}
	.bottomLi text{
		color: #00b42a;
	}
</style>